package com.ducquoc.examreviewdegreea1;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

import android.app.Activity;
import android.os.Environment;

public class DocReadWriteFile extends Activity {
	
	ArrayList<String> arr = new ArrayList<String>();
	String data, currentDate = "", currentVersion = "", currentStatus = "null";
	int run = 1;
	
	public void CreateFile()
	{	
		File direct = new File("sdcard/ExamReviewDegreeA1/");

		if (direct.mkdir()) { //Tao file
			// Tao moi va ghi du lieu mac dinh ban dau vao file test_database.txt
			try {
				if (!direct.exists()) {//Kiem tra ton tai
					direct.mkdirs(); //Tao file
				}
				File gpxfile = new File(direct, "test_database.txt");
				FileWriter writer = new FileWriter(gpxfile);
				writer.append("28-10-1990\n");
				writer.append("1\n");
				writer.append("null");
				writer.flush();
				writer.close();
				
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public ArrayList<String> ReadFile()
	{
		try {
			//Doc du lieu trong file test_database.txt nam trong thu muc ExamReviewDegreeA1
			File sdcard = Environment.getExternalStorageDirectory();

			// Lay duong dan toi file
			File file = new File(sdcard, "ExamReviewDegreeA1/test_database.txt");

			// Read text from file
			StringBuilder text = new StringBuilder();
			BufferedReader br = new BufferedReader(new FileReader(file));
			while ((data = br.readLine()) != null) {
				text.append(data);
				text.append('\n');
				if (run == 1) {
					currentDate = data;
					arr.add(0, currentDate);
				} else if (run == 2) {
					currentVersion = data;
					arr.add(1, currentVersion);
				} else if (run == 3) {
					currentStatus = data;
					arr.add(2, currentStatus);
				}
				run = run + 1;
			}
			br.close();
		}
		catch(Exception ex)
		{
			//Thu muc va file chua ton tai thi tien hanh tao moi
			CreateFile();
			//Sau khi tao moi thi doc du lieu trong file test_database.txt gan vao mang arr
			ReadFile();
		}
		//Tra ve mang
		return arr;
	}
	
	public void WriteFile(String dateNew, String versionNew, String statusNew) {
		File direct = new File(Environment.getExternalStorageDirectory()
				.getAbsolutePath() + "/ExamReviewDegreeA1/");

		// Ghi du lieu moi vao file test_database.txt/
		try {
			File gpxfile = new File(direct, "test_database.txt");
			FileWriter writer = new FileWriter(gpxfile);
			writer.append(dateNew + "\n");
			writer.append(versionNew + "\n");
			writer.append(statusNew);
			writer.flush();
			writer.close();
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
